<?php


namespace app\server;


use EasyWeChat\Factory;

class WeChat {
    protected $app;

    public function __construct () {
        $config=config('wechat');
        $this->app=Factory::officialAccount($config);
    }

    /**
     * 微信登录
     * @param $baseUrl
     * @return string|\think\response\Json
     */
    public function getCode($baseUrl) {
        //触发微信返回code码
        $config = config('wechat');
        if (empty($config['app_id'])) {
            return error('请检查微信配置');
        }
        $urlObj["appid"] = $config['app_id'];
        $urlObj["redirect_uri"] = "$baseUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE" . "#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
        return $url;
    }

    private function ToUrlParams($urlObj) {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }
        return trim($buff, "&");
    }

    public function getUser(){
        return $this->app->oauth->user();
    }

    /**
     * 获取临时二维码
     */
    public function temporary($value='foo'){
        return $this->app->qrcode->temporary($value, 6 * 24 * 3600);
    }

    /**
     * 获取永久二维码
     */
    public function forever($value='foo'){
        return $this->app->qrcode->forever($value);
    }

    /**
     * 获取二维码地址
     */
    public function getQrcodeUrl($ticket){
        return $this->app->qrcode->url($ticket);
    }
}
